//查询产品列表
import classifyData from "./onSaleData";

export const initPageInfo = () => {
  //查询参数
  classifyData.tParam.searchParam.name = "";
  classifyData.tParam.searchParam.code = "";
  classifyData.tParam.searchParam.sourceCode = "";
  classifyData.tParam.searchParam.state = 3;
  classifyData.tParam.searchParam.startTime = null;
  classifyData.tParam.searchParam.endTime = null;
  classifyData.tParam.searchParam.collectionCategories.splice(0);

  //分页
  classifyData.tPage.listPage.pageNum = 1;
  classifyData.tPage.listPage.pageSize = 40;
  classifyData.tPage.listPage.total = 0;

  //数据
  classifyData.tData.productList.splice(0);
}

export const queryProductList = (self) => {
  let params = classifyData.tParam.searchParam;
  params.pageNum = classifyData.tPage.listPage.pageNum;
  params.pageSize = classifyData.tPage.listPage.pageSize;
  self.$Spin.show();
  self.$apiProduct.findImportedProducts(params).then(response => {
    self.$Spin.hide();
    classifyData.tData.productList.splice(0);
    if(response.success) {
      let page = response.result;
      if(page.list != null) {
        classifyData.tData.productList.push(...page.list);
      }
      classifyData.tPage.listPage.total = page.total;
    }else{
      classifyData.tPage.listPage.total = 0;
      self.$Message.error(response.errorMessage);
    }
  });
}

/**
 * @param categories 所有分类数据
 * @param checkedCategories 选中的分类
 * */
export const makeCategoryTree = (categories, checkedCategoryIds) => {
  if(categories == null || categories.length == 0) {
    return [];
  }
  let categoryTree = [];
  for(let cat1 of categories) {
    let nodesLvl2 = [];
    if(cat1.children!=null && cat1.children.length>0) {
      for(let cat2 of cat1.children) {
        let nodesLvl3 = [];
        if(cat2.children!=null && cat2.children.length>0) {
          if(checkedCategoryIds==null || checkedCategoryIds.length==0) {
            for(let cat3 of cat2.children) {
              let nodeLvl3 = {title: cat3.label, value: cat3.value, level: cat3.level, checked: false};
              nodesLvl3.push(nodeLvl3);
            }
          }else{
            for(let cat3 of cat2.children) {
              let isChecked = checkedCategoryIds.indexOf(cat3.value) >= 0;
              let nodeLvl3 = {title: cat3.label, value: cat3.value, level: cat3.level, checked: isChecked};
              nodesLvl3.push(nodeLvl3);
            }
          }
        }
        let nodeLvl2 = {title: cat2.label, value: cat2.value, level: cat2.level, children: nodesLvl3};
        nodesLvl2.push(nodeLvl2);
      }
    }
    let nodeLvl1 = {title: cat1.label, value: cat1.value, level: cat1.level, children: nodesLvl2};
    categoryTree.push(nodeLvl1);
  }
  return categoryTree;
}


export const saveProductCategories = (self) => {
  let params = classifyData.tParam.modifyParam;
  self.$Spin.show();
  self.$apiProduct.updateClassifications(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("设置产品分类成功！");
      classifyData.tStatus.classifyModal.isShow = false;
      queryProductList(self);
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

export const onlineProduct = (self, productId) => {
  self.$Spin.show();
  self.$apiProduct.getProductById({id: productId}).then(responseProduct => {
    self.$Spin.hide();
    if(responseProduct.success) {
      let product = responseProduct.result;

      let isSorted = isPriceSorted(product.productPriceList);
      if(!isSorted) {
        self.$Message.error({content:"产品档位价格不能比前面的档位价格高！", duration: 2});
        return;
      }

      if(product.classificationList==null || product.classificationList.length==0) {
        self.$Message.error({content: "产品尚未分配分类，无法上架！", duration: 2});
        return;
      }
      self.$Modal.confirm({
        title: "确认",
        content: "确定将此产品上架吗？",
        onOk() {
          let params = {id: product.product.id, code: product.product.code, state: product.product.state == 0 ? -1 : 0};
          self.$Spin.show();
          self.$apiProduct.changeProductState(params).then(response => {
            self.$Spin.hide();
            if(response.success) {
              self.$Message.success("提交成功！");
              queryProductList(self);
            }else{
              self.$Message.error(response.errorMessage);
            }
          }).catch(() => {
            self.$Message.error("提交失败！");
          });
        }
      });
    }else{
      self.$Message.error(responseProduct.errorMessage);
    }
  }).catch(() => {
    self.$Message.error("产品信息查询失败！");
  }).catch(() => {
    self.$Spin.hide();
  });
}

export const deleteProduct = (self, productId) => {
  self.$Modal.confirm({
    title: "确认",
    content: "删除后将无法恢复，确定要删除此产品吗？",
    onOk() {
      let params = {productId: productId};
      self.$Spin.show();
      self.$apiProduct.realDeleteProduct(params).then(response => {
        self.$Spin.hide();
        if(response.success) {
          self.$Message.success("产品删除成功！");
          queryProductList(self);
        }else{
          self.$Message.error(response.errorMessage);
        }
      }).catch(() => {
        self.$Spin.hide();
        self.$Message.error("删除产品失败！")
      })
    }
  })
}

export const isPriceSorted = (prices) => {
  if(prices.length == 1) {
    return true;
  }

  let isPriceSorted = true;
  for(let i=0; i<prices.length; i++) {
    if(i < prices.length - 1)
    if(prices[i].price <= prices[i+1].price) {
      isPriceSorted = false;
    }
  }
  return isPriceSorted;
}
